package com.fingard.dsp.bank.directbank.cmb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IVirtualOrder;
import com.fingard.dsp.bank.reqrespobj.virtual.ReqQueryVirtualOrder;
import com.fingard.dsp.bank.reqrespobj.virtual.ReqVirtualOrder;
import com.fingard.dsp.bank.reqrespobj.virtual.RetAtsQueryVirtualOrder;
import com.fingard.dsp.bank.reqrespobj.virtual.RetAtsVirtualOrder;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

public class CMB01VirtualOrder extends CMB01Base implements IVirtualOrder {
    public RetAtsVirtualOrder submitVirtualOrder(ReqVirtualOrder p_req) throws Exception {
        RetAtsVirtualOrder retAts = new RetAtsVirtualOrder();
        retAts.rdSeq = p_req.rdSeq;
        retAts.virtualAccount = p_req.virtualAccount;
        try {
            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "NTDMAADD";
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter, tmpBnkHeader);
            xmlWriter.writeStartElement("NTDMAADDX");
            xmlWriter.writeElementString("ACCNBR", p_req.ownAct);
            xmlWriter.writeElementString("DMANBR", p_req.virtualAccount);
            xmlWriter.writeElementString("DMANAM", p_req.virtualName);
            xmlWriter.writeElementString("OVRCTL", getBankConfig().getValueAsString("ovrCtlFlag"));
            xmlWriter.writeElementString("BCKTYP", getBankConfig().getValueAsString("backType"));
            xmlWriter.writeElementString("CLSTYP", getBankConfig().getValueAsString("clsType"));
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                    String tmpRetMsg = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if (!StringHelper.isNullOrEmpty(tmpRetCode)) {
                        retAts.respCode = "0";
                        retAts.respInfo = tmpRetMsg;
                        if ("0".equals(tmpRetCode)) {
                            retAts.transState = "2";
                        } else {
                            retAts.transState = "3";
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = "银行返回报文格式有误！";
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = tmpStrRet[1];
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }
        return retAts;
    }


    public RetAtsQueryVirtualOrder queryVirtualPay(ReqQueryVirtualOrder p_req) throws Exception {
        RetAtsQueryVirtualOrder retAts = new RetAtsQueryVirtualOrder();
        boolean isFinished = false;
        try {
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req.getDateTo());

            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;

            RetAtsQueryVirtualOrder todayTrans = new RetAtsQueryVirtualOrder();
            RetAtsQueryVirtualOrder hisTrans = new RetAtsQueryVirtualOrder();
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo) {
                String isSetSleep = getBankConfig().getValueAsString("useSleepGetQuery");
                if ("true".equals(isSetSleep.toLowerCase())) {
                    long realSleepTime = getBankConfig().getValueAsInt("QuerySleepTime");
                    if (realSleepTime < 0) {
                        realSleepTime = 0;
                    }
                    Thread.sleep(realSleepTime * 1000);
                }
                if (DateHelper.compareDay(tmpCalendarFrom.getTime(), new Date()) == 0) {
                    todayTrans = d_Virtual01_NTDMTLST(p_req);
                    retAts = todayTrans;
                    if ("0".equals(retAts.respCode)) {
                        isFinished = true;
                        break;
                    }
                } else {
                    hisTrans = d_Virtual01_NTDMTHLS(p_req, Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    retAts = hisTrans;
                    if ("0".equals(retAts.respCode)) {
                        isFinished = true;
                        break;
                    }
                }
                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
            }
            if (!isFinished) {
                retAts = new RetAtsQueryVirtualOrder();
                retAts.respCode = "0";
                retAts.rdSeq = p_req.rdSeq;
                retAts.transState = "4";
                retAts.respInfo = "所查时间范围内未匹配到交易！";
                return retAts;
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = e.getMessage();
            e.printStackTrace();
            WriteBankLogLn(e);
        }
        return retAts;
    }

    public RetAtsQueryVirtualOrder d_Virtual01_NTDMTLST(ReqQueryVirtualOrder p_req) throws Exception {
        RetAtsQueryVirtualOrder retAts = new RetAtsQueryVirtualOrder();
        retAts.rdSeq = p_req.rdSeq;
        try {
            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "NTDMTLST";
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            writeCommonHeader(xmlTextWriter, tmpBnkHeader);
            xmlTextWriter.writeStartElement("NTDMTLSTY");
            xmlTextWriter.writeElementString("ACCNBR", p_req.ownAct);
            xmlTextWriter.writeElementString("DMANBR", p_req.virtualAccount);//虚拟户编号
            xmlTextWriter.writeEndDocument();

            String[] resutlt = sendToBank(xmlTextWriter.toXmlString());

            String moneyWay = p_req.moneyWay;
            String amount = p_req.amount;
            String ownAct = p_req.ownAct;
            String virtualAccount = p_req.virtualAccount;
            if (resutlt[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1].trim(), tmpSbMsg);
                if (tmpBkReader != null) {
                    String respCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD").trim();
                    String respInfo = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if ("0".equals(respCode)) {
                        while (tmpBkReader.read("/CMBSDKPGK/NTDMTLSTZ")) {
                            XElement readXElement = tmpBkReader.readedXElement;
                            String tmpTRXAMT = readXElement.getSingleTextNotNull("TRXAMT");//交易金额
                            String tmpAMTCDR = readXElement.getSingleTextNotNull("TRXDIR");//AMTCDR 借贷标记 C:贷；D:借
                            String tmpACCNBR = readXElement.getSingleTextNotNull("ACCNBR");//账号
                            String tmpDMANBR = readXElement.getSingleTextNotNull("DMANBR");//虚拟户编号
                            if ("D".equals(tmpAMTCDR)) {
                                tmpAMTCDR = "1";
                            } else if ("C".equals(tmpAMTCDR)) {
                                tmpAMTCDR = "2";
                            } else {
                                throw new Exception("无效的AMTCDR借贷标记：" + tmpAMTCDR);
                            }
                            retAts.respCode = "0";
                            retAts.respInfo = respInfo;
                            retAts.oppBankAccount = p_req.ownAct;

                            if (moneyWay.equals(tmpAMTCDR) && amount.equals(tmpTRXAMT) && ownAct.equals(tmpACCNBR) && virtualAccount.equals(tmpDMANBR)) {
                                retAts.transState = "2";
                                retAts.ourBankAccount = tmpACCNBR;
                                retAts.virtualAccount = readXElement.getSingleTextNotNull("DMANBR");
                                retAts.askNumber = readXElement.getSingleTextNotNull("TRXNBR");
                                retAts.payDate = Format.Date8Format.format(new Date());
                                String tmpTRXTIM = readXElement.getSingleTextNotNull("TRXTIM");
                                retAts.payTime = Format.Time6Format.format(Format.Time6Format.parse(tmpTRXTIM));
                                retAts.oppBankAccount = readXElement.getSingleTextNotNull("RPYACC");
                                retAts.oppBankAccountName = readXElement.getSingleTextNotNull("RPYNAM");
                                retAts.moneyWay = p_req.moneyWay;
                                retAts.amount = p_req.amount;
                                retAts.memo = readXElement.getSingleTextNotNull("TRXTXT");
                                break;
                            } else {
                                retAts.respCode = "-1";
                            }
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = respInfo;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = resutlt[1];
            }
        } catch (Exception ex) {
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn("查询明细异常:" + ex);
        }
        return retAts;
    }

    public RetAtsQueryVirtualOrder d_Virtual01_NTDMTHLS(ReqQueryVirtualOrder p_req, String queryDate) throws Exception {
        RetAtsQueryVirtualOrder retAts = new RetAtsQueryVirtualOrder();
        retAts.rdSeq = p_req.rdSeq;
        try {
            CMB01Header tmpBnkHeader = new CMB01Header();
            tmpBnkHeader.FUNNAM = "NTDMTHLS";
            XmlTextWriter xmlTextWriter = new XmlTextWriter();
            writeCommonHeader(xmlTextWriter, tmpBnkHeader);
            xmlTextWriter.writeStartElement("NTDMTHLSY");
            xmlTextWriter.writeElementString("ACCNBR", p_req.ownAct);
            xmlTextWriter.writeElementString("DMANBR", p_req.virtualAccount);
            xmlTextWriter.writeElementString("BEGDAT", queryDate);
            xmlTextWriter.writeElementString("ENDDAT", queryDate);
            xmlTextWriter.writeEndDocument();

            String[] resutlt = sendToBank(xmlTextWriter.toXmlString());

            String moneyWay = p_req.moneyWay;
            String amount = p_req.amount;
            String ownAct = p_req.ownAct;
            String virtualAccount = p_req.virtualAccount;
            if (resutlt[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(resutlt[1].trim(), tmpSbMsg);
                if (tmpBkReader != null) {
                    String respCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD").trim();
                    String respInfo = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                    if ("0".equals(respCode)) {
                        while (tmpBkReader.read("/CMBSDKPGK/NTDMTHLSZ")) {
                            XElement readXElement = tmpBkReader.readedXElement;
                            String tmpTRXAMT = readXElement.getSingleTextNotNull("TRXAMT");
                            String tmpAMTCDR = readXElement.getSingleTextNotNull("TRXDIR");//AMTCDR 借贷标记 C:贷；D:借
                            String tmpACCNBR = readXElement.getSingleTextNotNull("ACCNBR");
                            String tmpDMANBR = readXElement.getSingleTextNotNull("DMANBR");//虚拟户编号
                            if ("D".equals(tmpAMTCDR)) {
                                tmpAMTCDR = "1";
                            } else if ("C".equals(tmpAMTCDR)) {
                                tmpAMTCDR = "2";
                            } else {
                                throw new Exception("无效的AMTCDR借贷标记：" + tmpAMTCDR);
                            }
                            retAts.respCode = "0";
                            retAts.respInfo = respInfo;
                            retAts.oppBankAccount = p_req.ownAct;

                            if (moneyWay.equals(tmpAMTCDR) && amount.equals(tmpTRXAMT) && ownAct.equals(tmpACCNBR) && virtualAccount.equals(tmpDMANBR)) {
                                retAts.transState = "2";
                                retAts.ourBankAccount = tmpACCNBR;
                                retAts.virtualAccount = readXElement.getSingleTextNotNull("DMANBR");
                                retAts.askNumber = readXElement.getSingleTextNotNull("TRXNBR");
                                String tmpTRXDAT = readXElement.getSingleTextNotNull("TRXDAT");
                                retAts.payDate = Format.Date8Format.format(Format.Date8Format.parse(tmpTRXDAT));
                                String tmpTRXTIM = readXElement.getSingleTextNotNull("TRXTIM");
                                retAts.payTime = Format.Time6Format.format(Format.Time6Format.parse(tmpTRXTIM));
                                retAts.oppBankAccount = readXElement.getSingleTextNotNull("RPYACC");
                                retAts.oppBankAccountName = readXElement.getSingleTextNotNull("RPYNAM");
                                retAts.moneyWay = p_req.moneyWay;
                                retAts.amount = p_req.amount;
                                retAts.memo = readXElement.getSingleTextNotNull("TRXTXT");
                                break;
                            } else {
                                retAts.respCode = "-1";
                            }
                        }
                    } else {
                        retAts.respCode = "-1";
                        retAts.respInfo = respInfo;
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = tmpSbMsg.toString();
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = resutlt[1];
            }
        } catch (Exception ex) {
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            ex.printStackTrace();
            WriteBankLogLn("查询明细异常:" + ex);
        }
        return retAts;
    }
}